// dh-nurses 云对象 - 护士管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete, getUserById, listNurses } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-nurses] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 解析JWT Token获取payload
 */
function parseToken(token) {
	if (!token || typeof token !== 'string') return null;
	try {
		const parts = token.split('.');
		if (parts.length !== 3) return null;
		const payload = Buffer.from(parts[1], 'base64').toString('utf-8');
		return JSON.parse(payload);
	} catch (error) {
		console.error('[dh-nurses] 解析token失败:', error);
		return null;
	}
}

/**
 * 获取护士职称文本
 */
function getTitleText(titleLevel) {
	const titleMap = {
		0: '护士',
		1: '护师',
		2: '主管护师',
		3: '副主任护师',
		4: '主任护师'
	};
	return titleMap[titleLevel] || '未知';
}

/**
 * 从 dh-common 获取护士姓名并附加职称信息
 */
async function enrichNurseInfo(nurseData) {
	if (!nurseData || !nurseData.user_id) {
		return nurseData;
	}
	
	try {
		// 使用统一的用户查询工具获取用户信息（自动解密）
		// getUserById 已经通过 matchesRoleFilter 检查了角色（nurse 优先级 30 > 0，会通过检查）
		const userInfo = await getUserById(nurseData.user_id, 'default', false, true);
		
		if (userInfo) {
			const realName = userInfo.realName || userInfo.displayName || '未知';
			const titleText = getTitleText(nurseData.title_level);
			
			return {
				...nurseData,
				nurse_name: realName,
				title_text: titleText
			};
		}
		
		// 如果获取用户信息失败，返回默认值
		return {
			...nurseData,
			nurse_name: '未知',
			title_text: getTitleText(nurseData.title_level)
		};
	} catch (error) {
		console.error('[enrichNurseInfo] 获取护士信息失败:', error);
		// 出现异常时，返回默认值
		return {
			...nurseData,
			nurse_name: '未知',
			title_text: getTitleText(nurseData.title_level)
		};
	}
}

/**
 * 批量附加护士信息
 */
async function enrichNursesList(nursesList) {
	if (!Array.isArray(nursesList) || nursesList.length === 0) {
		return nursesList;
	}
	
	// 获取所有唯一的用户ID
	const userIds = [...new Set(nursesList.map(n => n.user_id).filter(Boolean))];
	
	if (userIds.length === 0) return nursesList;
	
	try {
		// 使用dh-common模块查询护士列表
		const nursesResult = await listNurses({ limit: 1000 });
		
		// 检查查询结果
		if (nursesResult.code !== 200) {
			console.warn(`[enrichNursesList] 查询护士列表失败: ${nursesResult.message}`);
			throw new Error(nursesResult.message);
		}
		
		// 过滤出我们需要的护士
		const nurses = nursesResult.data.filter(nurse => userIds.includes(nurse._id));
		
		// 构建用户ID到姓名的映射
		const nurseMap = {};
		nurses.forEach(nurse => {
			nurseMap[nurse._id] = nurse.realName || nurse.displayName || '未知';
		});
		
		// 附加护士姓名和职称
		return nursesList.map(nurse => ({
			...nurse,
			nurse_name: nurseMap[nurse.user_id] || '未知',
			title_text: getTitleText(nurse.title_level)
		}));
	} catch (error) {
		console.error('[enrichNursesList] 批量获取护士信息失败:', error);
		return nursesList.map(nurse => ({
			...nurse,
			nurse_name: '未知',
			title_text: getTitleText(nurse.title_level)
		}));
	}
}

module.exports = {

	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const clientInfo = this.getClientInfo();
		const tokenString = clientInfo?.uniIdToken;
		const tokenPayload = parseToken(tokenString);

		const writeMethods = ['create', 'update', 'delete', 'batch'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!tokenPayload?.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	/**
	 * 获取可用的护士用户列表（未创建护士信息的护士角色用户）
	 */
	async getAvailableNurseUsers() {
		try {
			// 1. 获取所有已有护士档案的用户ID
			const nursesRes = await db.collection('dh-nurses')
				.where({
					is_deleted: _.neq(true)
				})
				.field({
					user_id: true
				})
				.get();
			
			const existingUserIds = nursesRes.data.map(n => n.user_id);
			
			// 2. 使用dh-common模块查询所有护士
			const nursesResult = await listNurses({ limit: 1000 });
			
			// 检查查询结果
			if (nursesResult.code !== 200) {
				return formatResponse(500, null, `查询护士列表失败: ${nursesResult.message}`);
			}
			
			// 3. 过滤掉已有护士档案的用户
			let availableUsers = nursesResult.data.filter(user => !existingUserIds.includes(user._id));
			
			return formatResponse(200, availableUsers, '查询成功');
		} catch (error) {
			return formatError(error, '获取可用护士用户列表失败');
		}
	},

	/**
	 * 获取护士详情
	 */
	async getNurseById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '护士ID不能为空');
			}

			const res = await db.collection('dh-nurses').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '护士不存在');
			}

			// 附加护士姓名和职称信息
			const enrichedNurse = await enrichNurseInfo(res.data[0]);
			return formatResponse(200, enrichedNurse);
		} catch (error) {
			return formatError(error, '获取护士详情失败');
		}
	},

	/**
	 * 获取护士列表
	 */
	async listNurses(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;

		// 默认不显示已删除记录
		query.is_deleted = false;
		
		// 查询总数
		const countRes = await db.collection('dh-nurses')
			.where(query)
			.count();

			const totalCount = countRes.total || 0;

			// 查询护士列表
			const nursesRes = await db.collection('dh-nurses')
				.where(query)
				.skip(skip)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get();

			// 批量附加护士姓名和职称信息
			const enrichedNurses = await enrichNursesList(nursesRes.data);

			return formatResponse(200, enrichedNurses, 'success', { count: totalCount });
		} catch (error) {
			return formatError(error, '获取护士列表失败');
		}
	},

	/**
	 * 创建护士
	 */
	async createNurse(data) {
		try {
			if (!data.user_id) {
				return formatResponse(400, null, '用户ID不能为空');
			}

			let nurseData = {
				user_id: data.user_id,
				title_level: data.title_level || 0,
				license_no: data.license_no || '',
				department: data.department || '',
				education_background: data.education_background || '',
				years_experience: data.years_experience || 0,
				introduction: data.introduction || '',
				working_status: data.working_status !== undefined ? data.working_status : 0,
				is_active: data.is_active !== undefined ? data.is_active : true,
				is_deleted: false,  // 软删除字段，默认未删除
				create_time: Date.now(),
				update_time: Date.now()
			};
			
			// 如果有照片，添加photo字段
			if (data.photo) {
				nurseData.photo = data.photo;
			}

			// 🏥 自动挂载医院ID（单一医院系统特性）
			nurseData = await autoMountHospitalId(nurseData);

			const res = await db.collection('dh-nurses').add(nurseData);
			return formatResponse(201, { _id: res.id }, '护士创建成功');
		} catch (error) {
			return formatError(error, '创建护士失败');
		}
	},

	/**
	 * 更新护士信息
	 */
	async updateNurse(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '护士ID不能为空');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			// 移除不应该更新的字段
			delete updateData._id;
			delete updateData.user_id;
			delete updateData.create_time;

			await db.collection('dh-nurses').doc(id).update(updateData);
			return formatResponse(200, null, '护士信息更新成功');
		} catch (error) {
			return formatError(error, '更新护士失败');
		}
	},

	/**
	 * 删除护士
	 */
	async deleteNurse(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '护士ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-nurses', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '护士已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除护士失败');
		}
	},

	/**
	 * 批量删除护士
	 */
	async batchDeleteNurses(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-nurses', ids, uniIdToken?.uid || '', reason);
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	}
};

